package Producer_Consumer;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-08
 * Time: 23:38
 */
public class ArrayBlockingQueue {
    private int head = 0;
    private int tail = 0;
    private int useSize = 0;
    private final Runnable[] queue;

    public ArrayBlockingQueue(int capacity){
        queue = new Runnable[capacity];
    }

    public synchronized void put(Runnable runnable) throws InterruptedException {
        while (isFull()){
            this.wait();
        }
        queue[tail] = runnable;
        tail++;
        if (tail >= queue.length){
            tail = 0;
        }
        useSize++;
        this.notify();
    }

    public synchronized Runnable take() throws InterruptedException {
        while (useSize <= 0){
            this.wait();
        }
        Runnable runnable = queue[head];
        head++;
        if (head >= queue.length){
            head = 0;
        }
        useSize--;
        this.notify();
        return runnable;
    }

    public boolean isFull(){
        return useSize >= queue.length;
    }
}
